package com.yiyuzi.admin.token.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiyuzi.admin.common.utils.UserUtils;
import com.yiyuzi.admin.token.TokenDao;
import com.yiyuzi.admin.token.domain.TokenEntity;
import com.yiyuzi.admin.user.domain.entity.UserEntity;
import com.yiyuzi.admin.user.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.Date;

/**
 * @author yiyuzi
 * @date 2021/5/14 17:10
 */

@Service
@Transactional
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {
    // 一小时
    private final static int EXPIRE = 3600000;

    @Resource
    private UserService userService;

    private String createToken() {
        return UserUtils.getMD5Str(UUID.randomUUID().toString());
    }

    @Override
    public String createToken(Long userId) {
        String token = this.createToken();
        boolean flag = false;
        TokenEntity tokenEntity = this.getOne(new QueryWrapper<TokenEntity>().eq("user_id", userId));
        if (tokenEntity == null){
            tokenEntity = new TokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            flag = this.save(tokenEntity);
        }else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(new Date(new Date().getTime() + EXPIRE * 8 ));
            flag = this.updateById(tokenEntity);
        }

        if (flag)
            return token;
        else
            return null;
    }

    @Override
    public boolean isValid(String token) {
        if (token == null){
            return false;
        }
        if (this.getOne(new QueryWrapper<TokenEntity>().eq("token", token)) == null){
            return false;
        }
        Date now = new Date();
        Date tokenCreateTime = this.getOne(new QueryWrapper<TokenEntity>().eq("token", token)).getUpdateTime();
        return now.compareTo(new Date(tokenCreateTime.getTime() + EXPIRE )) < 0;
    }

    @Override
    public TokenEntity getByToken(String token) {
        return this.getOne(new QueryWrapper<TokenEntity>().eq("token", token));
    }

    @Override
    public UserEntity getUserByToken(String token) {
        TokenEntity tokenEntity = this.getOne(new QueryWrapper<TokenEntity>().eq("token", token));
        if (tokenEntity == null)
            return null;
        return userService.getById(tokenEntity.getUserId());
    }
}
